package com.springboot.apiexample.web;

import com.springboot.apiexample.annotation.ApiIdempotentInterceptor;
import com.springboot.apiexample.annotation.RateLimitInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * web请求统一拦截器
 *
 * @author NiJo_H
 * @version 1.0
 * @date 2019/8/22 22:00
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 跨域支持
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "HEAD", "OPTIONS",
                "DELETE");
    }

    /**
     * 添加类型转换器和格式化器
     *
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, LocalDate.class, s -> {
            if (StringUtils.hasText(s)) {
                return LocalDate.parse(s);
            }
            return null;
        });
        registry.addConverter(String.class, LocalDateTime.class, s -> {
            if (StringUtils.hasText(s)) {
                return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse(s, LocalDateTime::from);
            }
            return null;
        });
        registry.addConverter(String.class, LocalTime.class, s -> {
            if (StringUtils.hasText(s)) {
                return LocalTime.parse(s);
            }
            return null;
        });
        registry.addConverter(String.class, YearMonth.class, s -> {
            if (StringUtils.hasText(s)) {
                return YearMonth.parse(s);
            }
            return null;
        });
    }

    /**
     * 幂等性拦截器
     */
    @Bean
    public ApiIdempotentInterceptor apiIdempotentInterceptor() {
        return new ApiIdempotentInterceptor();
    }

    /**
     * 限流器
     * */
    @Bean
    public RateLimitInterceptor rateLimitInterceptor(){
        return new RateLimitInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 幂等性拦截器
        registry.addInterceptor(apiIdempotentInterceptor());
        //限流器
        registry.addInterceptor(rateLimitInterceptor());
    }
}
